#include "heap.h"
#include <assert.h>
#include <stdlib.h>
using namespace std;
void HeapInit(Heap* hp)
{
	assert(hp);
	hp->_a = nullptr;
	hp->_size = hp->_capacity = 0;

}

void HeapDestory(Heap* hp)
{
	assert(hp);
	free(hp->_a);
	hp->_a = nullptr;
	hp->_size = hp->_capacity = 0;

}

void HeapPush(Heap* hp, HPDataType x)
{
	assert(hp);
	// 检查容量
	if (hp->_size == hp->_capacity) {
		int newCapacity = hp->_capacity == 0 ? 4 : hp->_capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(hp->_a, sizeof(HPDataType) * newCapacity);
		if (tmp == nullptr) {
			perror("realloc fail");
			exit(-1);
		}
		hp->_a = tmp;
		hp->_capacity = newCapacity;
	}
	hp->_a[hp->_size] = x;
	hp->_size++;
	AdjustUp(hp->_a, hp->_size - 1);
	

}

void HeapPop(Heap* hp)
{
	assert(hp);
	assert(hp->_size > 0); // 堆不能为空
	// 将堆顶元素与末尾元素交换
	HPDataType tmp = hp->_a[0];
	hp->_a[0] = hp->_a[hp->_size - 1];
	hp->_a[hp->_size - 1] = tmp;
	// 删除末尾元素（即原堆顶）
	hp->_size--;
	// 从新的根节点开始向下调整
	AdjustDown(hp->_a, hp->_size, 0);
}

HPDataType HeapTop(Heap* hp)
{
	assert(hp && hp->_size > 0);
	return hp->_a[0];
}

int HeapSize(Heap* hp)
{
	return hp->_size;
}

int HeapEmpty(Heap* hp)
{
	return hp->_size == 0;
}

void AdjustUp(HPDataType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[parent] > a[child])
		{
			HPDataType tmp = a[child];
			a[child] = a[parent];
			a[parent] = tmp;
		    
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void AdjustDown(HPDataType* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] > a[child + 1])
		{
			child = child + 1;
		}
		if (a[child] < a[parent])
		{
			HPDataType tmp = a[child];
			a[child] = a[parent];
			a[parent] = tmp;

			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
	
	
}

void HeapSort(int* a, int n)
{
	Heap st;
	for (int i = 0; i < n; i++)
	{
		HeapPush(&st, a[i]);
	}
	for (int i = 0; i < n; i++)
	{
		a[i] = HeapTop(&st);
		HeapPop(&st);
	}
	HeapDestory(&st);
}
